/**
 * 角色管理
 */
 ({
 	launch : function() {
 		var me = this;
 		var perms = this.perms;
 		var role = {
 			browse : function() {
 				var _this = this;
				var datagrid = $("<table></table>");
				var tools = $('<div></div>');
				if(perms.add) {
					var addButton = $('<a href="#" class="icon-add"></a>').appendTo(tools);
					addButton.click(function() {
						_this.add(datagrid);
						return false;
					});
				}
				if(perms.remove) {
					var rmButton = $('<a href="#" class="icon-remove"></a>').appendTo(tools);
					rmButton.click(function() {
						$.messager.confirm("请确认：", "确认要删除所选角色吗？", function(isOk) {
							if(isOk) {
								var items = datagrid.datagrid("getChecked");
								var ids = [];
								$(items).each(function() {
									ids.push(this.id);
								});
								$.messager.mask().text("操作执行中，请稍后……");
								$.post(me.ctx + "/manager/role/remove", {ids : ids}, function(data) {
									if(data.success) {
										rmButton.hide();
										datagrid.datagrid("reload");
									}
									$.messager.mask('close');
								}, "json");							
							}
						});
						return false;
					});
				}
				
				var rlButton = $('<a href="#" class="icon-reload"></a>').appendTo(tools);
				rlButton.click(function() {
					datagrid.datagrid("reload");
					return false;
				});
				
				var win = me.createWindow('<div></div>', {
					title:"角色管理",
					width:550,
					height:300,
					tools : tools
				});
				var columns = [
				    	{field : 'checkbox', checkbox : true},
				        {field : 'id', title : '角色编号', width : 120},
				        {field : 'name', title : '角色名称', width : 120}
				    ];
				if(perms.edit) {
					columns.push({
						field : 'editor', title : '编辑', align:'center', formatter: function(value, row, index){
				        	return '<a class="l-btn l-btn-small l-btn-plain"><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text l-btn-empty">&nbsp;</span><span class="l-btn-icon icon-edit">&nbsp;</span></span></a>';
					}});
				}
				if(perms.permission) {
					columns.push({
						field : 'permission', title : '分配权限', align:'center', formatter: function(value, row, index){
				        	return '<a class="l-btn l-btn-small l-btn-plain"><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text l-btn-empty">&nbsp;</span><span class="l-btn-icon icon-permissions">&nbsp;</span></span></a>';
					}});
				}
				datagrid.appendTo(win);
				datagrid.datagrid({
					fit : true,
					url : me.ctx + "/manager/role/browse",
					selectOnCheck : false,
					checkOnSelect : false,
					singleSelect : true,
				    columns : [columns],
				    onClickCell : function(index, field, value) {
				    	var rows = datagrid.datagrid("getRows");
				    	if(field === "editor") {
				    		_this.edit(datagrid, rows[index]);
				    	} else if(field === "permission") {
				    		permission.manager(rows[index]);
				    	}
				    },
				    onCheckAll : function(rows) {
				    	if(rows.length > 0 && perms.remove) {
				    		rmButton.show();
				    	}
				    },
				    onUncheckAll : function(rows) {
				    	if(perms.remove) {
				    		rmButton.hide();
				    	}
				    },
				    onCheck : function(index, row) {
				    	if(perms.remove) {
				    		rmButton.show();
				    	}
				    },
				    onUncheck : function(index, row) {
				    	if(perms.remove && $(this).datagrid("getChecked").length < 1) {
				    		rmButton.hide();
				    	}
				    }, 
				    onLoadSuccess : function() {
				    	if(perms.remove) {
				    		rmButton.hide();
				    	}
				    }
				});
				return win;
 			}, 
 			add : function(datagrid) {
 				var _this = this;
				var footer = $('<div style="padding:5px;text-align:right;"></div>');
				var win = me.createWindow('<div></div>', {
					title:"角色添加",
					width:300,
					height:150,
					resizable:false,
					minimizable:false,
					maximizable:false,
					modal:true,
					footer:footer
				});
				var form = $('<form style="width:100%;" method="post"></form>').appendTo(win);
				form.form({
					url : me.ctx + "/manager/role/create",
					success: function(data){
						$.messager.mask("close");
				        var data = eval('(' + data + ')');
				        if (data.success){
				        	datagrid.datagrid("options").pageNumber = 1;
				            datagrid.datagrid("reload");
				            win.window("close");
				            $.messager.alert('提示：', "角色添加成功！", "info");
				        } else {
				        	$.messager.alert('提示：', data.message, "info");
				        }
				    }
				});
				var table = $('<table width="100%" class="form-table"></table>').appendTo($('<div style="padding:5px 5px;"></div>').appendTo(form));
				var row = table.row();
				row.cell("角色编号：", {width:"60px"});
				var field = $('<input type="text" name="id" />');
				row.cell(field);
				field.textbox({
					required: true,
					validType : ['letters_', 'maxlength[50]']
				});
				
				row = table.row();
				row.cell("角色名称：");
				field = $('<input type="text" name="name" />');
				row.cell(field);
				field.textbox({
					required: true,
					validType : ['maxlength[50]']
				});
				row = table.row();
				row.cell("排序：");
				field = $('<input type="text" name="index" value="' + (datagrid.datagrid("getData").total + 1) + '" />');
				row.cell(field);
				field.numberbox({
					min:1,
					precision:0,
					required: true
				});
				var saveButton = $('<a href="#">提交</a>').appendTo(footer);
				saveButton.linkbutton({
					iconCls : 'icon-ok',
					onClick : function() {
						if(form.form("validate")) {
							$.messager.mask().text("操作执行中，请稍后……");
							form.form("submit");
						}
						return false;						
					}
				});
				footer.append("&nbsp;");
				var cancelButton = $('<a href="#">取消</a>').appendTo(footer);
				cancelButton.linkbutton({
					iconCls: 'icon-cancel',
					onClick: function(){
						win.window("close");
						return false;						
					}
				});
 			}, 
 			edit : function(datagrid, role) {
 				var _this = this;
				var footer = $('<div style="padding:5px;text-align:right;"></div>');
				var win = me.createWindow('<div></div>', {
					title:"角色编辑",
					width:300,
					height:145,
					resizable:false,
					minimizable:false,
					maximizable:false,
					modal:true,
					footer:footer
				});
				var form = $('<form style="width:100%;" method="post"></form>').appendTo(win);
				form.form({
					url : me.ctx + "/manager/role/update",
					success: function(data){
						$.messager.mask("close");
				        var data = eval('(' + data + ')');
				        if (data.success){
				        	datagrid.datagrid("options").pageNumber = 1;
				            datagrid.datagrid("reload");
				            win.window("close");
				            $.messager.alert('提示：', "角色更新成功！", "info");
				        } else {
				        	$.messager.alert('提示：', data.message, "info");
				        }
				    }
				});
				var table = $('<table width="100%" class="form-table"></table>').appendTo($('<div style="padding:5px 5px;"></div>').appendTo(form));
				var row = table.row();
				row.cell("角色编号：", {width:"60px"});
				var fieldContainer = row.cell(role.id);
				var field = $('<input type="hidden" name="id" />').appendTo(fieldContainer);
				
				row = table.row();
				row.cell("角色名称：");
				field = $('<input type="text" name="name" />');
				row.cell(field);
				field.textbox({
					required: true,
					validType : ['maxlength[50]']
				});
				row = table.row();
				row.cell("排序：");
				field = $('<input type="text" name="index" />');
				row.cell(field);
				field.numberbox({
					min:1,
					precision:0,
					required: true
				});
				var saveButton = $('<a href="#">提交</a>').appendTo(footer);
				saveButton.linkbutton({
					iconCls : 'icon-ok',
					onClick : function() {
						if(form.form("validate")) {
							$.messager.mask().text("操作执行中，请稍后……");
							form.form("submit");
						}
						return false;						
					}
				});
				footer.append("&nbsp;");
				var cancelButton = $('<a href="#">取消</a>').appendTo(footer);
				cancelButton.linkbutton({
					iconCls: 'icon-cancel',
					onClick: function(){
						win.window("close");
						return false;						
					}
				});
				form.form("load", role);
 			}
 			
 		};
 		var permission = {
 			manager : function(role) {
 				var footer = $('<div style="padding:5px;text-align:right;"></div>');
 				var win = me.createWindow('<div></div>', {
					title:"分配权限",
					width:300,
					height:400,
					resizable:false,
					minimizable:false,
					maximizable:false,
					modal:true,
					footer:footer
				});
				var tree = $('<ul></ul>').appendTo(win);
				tree.tree({
					url:me.ctx + "/manager/role/tree",
					method:"post",
					queryParams:{
						role_id:role.id
					},
					animate:true,
					checkbox:true
				});
				var saveButton = $('<a href="#">确定分配</a>').appendTo(footer);
				saveButton.linkbutton({
					iconCls : 'icon-ok',
					onClick : function() {
						$.messager.mask().text("操作执行中，请稍后……");
						var nodes = tree.tree("getChecked", ['checked','indeterminate']);
						var params = {
							role_id : role.id,
							app_ids : [],
							per_ids : []
						};
						$(nodes).each(function() {
							if(this.type === "app") {
								params.app_ids.push(this.id);
							} else if(this.type === "permission") {
								params.per_ids.push(this.id);
							}
						});
						$.post(me.ctx + "/manager/role/alloc", params, function(data) {
							$.messager.mask("close");
					        if (data.success){
					            $.messager.alert('提示：', "权限分配成功！", "info");
					        } else {
					        	$.messager.alert('提示：', data.message, "info");
					        }
						}, "json");
						return false;						
					}
				});
				footer.append("&nbsp;");
				var cancelButton = $('<a href="#">取消</a>').appendTo(footer);
				cancelButton.linkbutton({
					iconCls: 'icon-cancel',
					onClick: function(){
						win.window("close");
						return false;						
					}
				});
				return win;
 			}
 		};
 		role.browse();
 	}
 })